;
(function() {
	if (window.bridge) {
		return;
	}
	window.bridge = function() {
		var handlers = {},
		    callbacks = {},
            errorCallbacks = {},
			jsCallbackId = 0;

		function postMessage(name, data, flutterCallbackId, jsCallbackId, error) {
			if (flutterBridge) {
                var params = {
					"name": name,
					"data": data,
					"flutterCallbackId": flutterCallbackId,
					"jsCallbackId": jsCallbackId,
					"error": error,
				};
				flutterBridge.postMessage(JSON.stringify(params));
			}
		}

		return {
			"register": function(name, handler) {
				handlers[name] = handler;
			},
			"call": async function(name, data) {
				return new Promise((resolve, reject) => {
					var id = (jsCallbackId++).toString();
					callbacks[id] = resolve;
					errorCallbacks[id] = reject;
					postMessage(name, data, null, id, null);
				});
			},
			"receiveMessage": function(message) {
				console.log("jslog: " + message);
				var name = message.name;
				var data = message.data;
				var jsCallbackId = message.jsCallbackId;
				var flutterCallbackId = message.flutterCallbackId;
                var error = message.error;

				if (jsCallbackId) {
					if(error) {
						var jsErrorCallback = errorCallbacks[jsCallbackId];
						if (jsErrorCallback) {
							jsErrorCallback(error);
							delete errorCallbacks[jsCallbackId];
						}
					} else {
						var jsCallback = callbacks[jsCallbackId];
						if (jsCallback) {
							jsCallback(data);
							delete callbacks[jsCallbackId];
						}
					}
				} else {
					var flutterCallback;
					if (flutterCallbackId) {
						flutterCallback = function(data) {
							postMessage(name, data, flutterCallbackId);
						};
					}
					var handler = handlers[name];
					if (handler) {
						handler(data, flutterCallback)
					} else {
						postMessage(name, data, flutterCallbackId, null, null);
					}
				}
			}
		}
	}()
})();